package com.summer.controller;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.summer.entity.TbRole;
import com.summer.entity.TbUserinfo;
import com.summer.mapper.TbRoleMapper;
import com.summer.mapper.TbUserinfoMapper;
import com.summer.utils.JwtToken;
import com.summer.utils.MyUtil;
import com.summer.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author summer502
 * @since 2021-03-31
 */
@CrossOrigin
@RestController
@RequestMapping("/tb-role")
@Transactional
@Api(value = "TbRoleController", description = "权限api")

public class TbRoleController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required =false)
    private TbRoleMapper tbRoleMapper;
    HttpServletRequest request;
    @Autowired (required = false)//https://blog.csdn.net/qq_40147863/article/details/86103857
    private TbUserinfoMapper tbUserinfoMapper;
    /**
     * 超级管理员添加角色(可以有普通用户和协会组织和教师)"
     * @param role_name
     * @param Authorization
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("超级管理员添加角色(可以有普通用户和协会组织和教师)")
    @PostMapping("/teacher/addRole")
    @ResponseBody
    public ResponseEntity addRole(@RequestParam(required = true) String role_name,
                                     @RequestHeader String Authorization
                                    ) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //parentRoleId
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo tbUserinfo = JwtToken.unsign(token, TbUserinfo.class);
        //用户角色，分微信用户和老师用户，1代表微信用户，2代表老师用户,默认为微信用户
        if (tbUserinfo.getUserId()!=1&&tbUserinfo.getUserId()>0){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //根据user_jobNumber查询数据库是否有该用户存在，不存在则注册，存在则注册失败
        QueryWrapper<TbRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", role_name);
        TbRole tbRole = tbRoleMapper.selectOne(queryWrapper);
        //User userFromBase = userDao.selectById(user_name);
        if (tbRole == null){
            responseEntity = ResponseEntity.ok();
            TbRole tbRole1 = new TbRole();
            tbRole1.setRoleName(role_name);
            tbRoleMapper.insert(tbRole1);
            responseEntity.putDataValue("RoleId",tbRole1.getRoleId());
            responseEntity.putDataValue("msg","角色添加成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","角色添加失败");
        }
        return responseEntity;
    }

    /**
     * 超级管理员修改角色信息
     * @param role_id
     * @param role_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("超级管理员修改角色信息")
    @PutMapping("/web/updateRole")
    @ResponseBody
    public ResponseEntity updateRole(@RequestParam(required = true) int role_id, @RequestParam(required = false) String role_name, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getRoleId()!=1) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;

        } else {
            responseEntity = ResponseEntity.ok();
            TbRole tbRole = tbRoleMapper.selectById(role_id);
            tbRole.setRoleName(role_name);
            tbRoleMapper.updateById(tbRole);
            responseEntity.putDataValue("msg", "教师修改成功");
            return responseEntity;
        }
    }

    /**
     * 根据role_id查询角色
     * @param role_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据role_id查询角色")
    @PutMapping("/web/selectByRoleId")
    @ResponseBody
    public ResponseEntity selectByRoleId(@RequestParam(required = true) Integer role_id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getRoleId()==1) {
            responseEntity=ResponseEntity.ok();
            TbRole tbRole = tbRoleMapper.selectById(role_id);
            responseEntity.putDataValue("tbRole",tbRole);
            return responseEntity;
        }
        responseEntity=ResponseEntity.unauthorized();
        responseEntity.putDataValue("msg","没有权限");
        return responseEntity;
    }

    /**
     * 根据id删除角色信息
     * @param role_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据id删除角色信息")
    @PutMapping("/web/deleteRole")
    @ResponseBody
    public ResponseEntity deleteRole(@RequestParam(required = true) Integer role_id,@RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users=JwtToken.unsign(token,TbUserinfo.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }else if(users.getRoleId()==1) {
            TbRole tbRole = tbRoleMapper.selectById(role_id);
            if(tbRole!=null){
                int is_delete = 1;
                QueryWrapper<TbUserinfo> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("role_id",role_id);
                List<TbUserinfo> list=tbUserinfoMapper.selectList(queryWrapper);
                int role_id1=0;
                for (TbUserinfo tbUserinfo : list) {
                    tbUserinfo.setRoleId(role_id1);
                    tbUserinfoMapper.updateById(tbUserinfo);
                }
                tbRole.setIsDelete(is_delete);
                tbRoleMapper.updateById(tbRole);
                responseEntity=ResponseEntity.ok();
                responseEntity.putDataValue("msg","删除成功");
                return responseEntity;
            }
        }
        responseEntity=ResponseEntity.unauthorized();
        responseEntity.putDataValue("msg","没有权限");
        return responseEntity;
    }
    /**
     * 角色列表
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("角色列表")
    @PostMapping("/web/RolesList")
    @ResponseBody
    public ResponseEntity RolesList(@RequestHeader String Authorization,
                                       HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getRoleId()!=1){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        QueryWrapper<TbRole> wrapper = new QueryWrapper<>();
        List<TbRole> list = tbRoleMapper.selectList(wrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("list",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 统计角色数量
     */
    @ApiOperation("统计角色数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        int is_delete = 0;
        QueryWrapper<TbRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", is_delete);
        int  count =tbRoleMapper.selectCount(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }
//    /**
//     * 批量删除角色
//     * @param arr
//     * @param Authorization
//     * @return
//     */
//    @ApiOperation("批量删除角色")
//    @GetMapping("/web/deleteTeacherList")
//    @ResponseBody
//    public ResponseEntity deleteTeacherList(@RequestParam(required = true) int[] arr,
//                                            @RequestHeader String Authorization ) throws  IOException{
//        ResponseEntity responseData;
//        String token = Authorization;
//        //通过token解密出来的user对象
//        TbRole user = JwtToken.unsign(token, TbRole.class);
//        //判断token是否存在或过期
//        if (flag = myUtil.judgeToken(token)){
//            responseData = ResponseEntity.forbidden();
//            responseData.putDataValue("msg","token不存在或已过期");
//            return responseData;
//        }
//        if (user.getRoleId()!=1){
//            responseData = ResponseEntity.badRequest();
//            responseData.putDataValue("msg","权限错误");
//            responseData.putDataValue("timestamp",myUtil.getTime());
//            return responseData;
//        }
//        for (int teacher_id : arr) {
//            TbRole teacher = tbRoleMapper.selectById(teacher_id);
//            int is_delete = 1;
//            teacher.setIsDelete(is_delete);
//            tbRoleMapper.updateById(teacher);
//        }
//        responseData = ResponseEntity.ok();
//        responseData.putDataValue("msg", "批量删除数据成功");
//        return responseData;
//
//
//    }

}
